import React from 'react';
import { Form, DatePicker, Button, Input, Select, Tooltip, notification } from 'antd';
import { findAllRoom, findRoomBySize, findRoomByStartAndEndTime, findRoomByStartAndEndTimeAndSize, addMeeting } from '../api/meeting';

const FormItem = Form.Item;

class NewMeetingForm extends React.Component {
  state = {
    rooms: []
  }

  handleSubmit = (e) => {
    e.preventDefault();

    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return;
      }

      const startTime = fieldsValue['startTime'].toDate().getTime()
      const values = {
        ...fieldsValue,
        starttime: startTime,
        endtime: startTime + fieldsValue['length'] * 60 * 1000
      };
      console.log('Received values of form: ', values);

      addMeeting(values).then(res => {
        const { data } = res
        if (data.code === 0) {
          // notification.success({
          //   message: data.msg
          // })
          this.props.postSuccess()
        } else if (data.code === 1) {
          notification.error({
            message: data.msg
          })
        }
      }).catch(err => console.log(err))
    });
  }

  componentDidMount = () => {
    this.getRooms()
  }

  getRooms = async (roomOptions) => {
    let res
    if (roomOptions) {
      const { size, startTime, endTime } = roomOptions
      if (size) {
        if (startTime && endTime) {
          res = await findRoomByStartAndEndTimeAndSize({
            starttime: startTime,
            endtime: endTime,
            size,
          })
        } else {
          res = await findRoomBySize(size)
        }
      } else if (startTime && endTime) {
        res = await findRoomByStartAndEndTime({
          starttime: startTime,
          endtime: endTime,
        })
      } else {
        res = await findAllRoom()
      }
    } else {
      res = await findAllRoom()
    }

    if (!res) {
      this.setState({
        rooms: []
      })
    } else {
      const { data } = res
      let cval = this.props.form.getFieldValue('room')
      if (data.code === 0) {
        let lr = data.data.filter(val => val.id === cval)
        let flag = lr.length !== 0
        if (!flag) {
          if (cval) {
            this.props.form.setFieldsValue({
              room: '请选择会议室'
            })
          }
        }
        this.setState({
          rooms: data.data
        })
      } else {
        if (cval) {
          this.props.form.setFieldsValue({
            room: '无满足条件的会议室'
          })
        }
        this.setState({
          rooms: []
        })
      }
    }
  }

  getRoomOptions = (length) => {
    const vals = this.props.form.getFieldsValue(['startTime', 'length', 'size'])
    const startTime = vals['startTime'] ? vals['startTime'].toDate().getTime() : null
    length = length ? length : vals['length']
    const endTime = startTime ? startTime + length * 60 * 1000 : null
    return {
      startTime,
      endTime,
      size: vals['size']
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const config = {
      rules: [{ type: 'object', required: true, message: 'Please select time!' }],
    };
    return (
      <Form onSubmit={this.handleSubmit} style={{
        maxWidth: '800px',
        margin: 'auto'
      }}>
        <FormItem
          {...formItemLayout}
          label="会议开始时间"
        >
          {getFieldDecorator('startTime', config)(
            <DatePicker 
                showTime={{
                  format: 'HH:mm'
                }}
                format="YYYY-MM-DD HH:mm" 
                showToday={false}
                disabledDate={date => {
                  if(!date) return true
                  let d = date.toDate().getTime()
                  let now = new Date().getTime()
                  return d < now - 24 * 60 * 60 * 1000 || d >= now + 3 * 24 * 60 * 60 * 1000 // && d <= now 
                }}
                onOk={() => {
                  this.getRooms(this.getRoomOptions())
                }}
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="会议时长"
        >
          {getFieldDecorator('length', {rules: [
            { required: true },
          ]})(
            <Input
              placeholder="请输入会议时长"
              type="number"
              addonAfter="分钟"
              onChange={(e) => {
                const length = e.target.value
                const options = this.getRoomOptions(length)
                this.getRooms(options)
              }}
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="会议大致人数"
        >
          {getFieldDecorator('size', {rules: [
            { required: true },
          ]})(
            <Input
              placeholder="请输入会议大致人数"
              type="number"
              onChange={e => {
                const size = e.target.value
                this.getRooms({
                  ...this.getRoomOptions(),
                  size
                })
              }}
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="会议室"
        >
        <Tooltip placement="top" title="先选择会议时间段及会议人数可以过滤掉不符合条件的会议室">
          {getFieldDecorator('room', {rules: [
            { required: true },
          ]})(
              <Select placeholder="请选择会议室">
                {this.state.rooms.length ? this.state.rooms.map(room => (
                  <Select.Option key={room.id}>{`${room.id}会议室 容量: ${room.size}人`}</Select.Option>
                )) : ''
                }
              </Select>
          )}
        </Tooltip>
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="会议主题"
        >
          {getFieldDecorator('theme', {rules: [
            { required: true },
          ]})(
            <Input
              placeholder="请输入会议主题"
              type="text"
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="会议是否需要签到"
        >
          {getFieldDecorator('isSigned', {rules: [
            { required: true },
          ]})(
            <Select placeholder="请选择">
              <Select.Option key="0">需要签到</Select.Option>
              <Select.Option key="1">不需要签到</Select.Option>
            </Select>
          )}
        </FormItem>
        <FormItem
          wrapperCol={{
            xs: { span: 24, offset: 0 },
            sm: { span: 16, offset: 8 },
          }}
        >
          <Button type="primary" htmlType="submit">提交</Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedNewMeetingForm = Form.create()(NewMeetingForm);

export default WrappedNewMeetingForm
